<?php

#########################################################
#                                                       #
#  CC / CREDIT CARD payment method class                #
#  This module is used for real time processing of      #
#  Credit card data of customers.                       #
#                                                       #
#  Copyright (c) 2009-2010 Novalnet AG                  #
#                                                       #
#  Released under the GNU General Public License        #
#  novalnet_cc module Created By Dixon Rajdaniel        #
#  This free contribution made by request.              #
#  If you have found this script usefull a small        #
#  recommendation as well as a comment on merchant form #
#  would be greatly appreciated.                        #
#                                                       #
#  Version : novalnet_cc.php 1.0.1 2011-06-21           #
#                                                       #
#########################################################


class novalnet_cc {
  var $code;
  var $title;
  var $description;
  var $enabled;
  var $proxy;
  var $callback_type;
  var $is_ajax = false;
  var $db;

  function __construct() {
    global $order,$db;
    $this->code         = 'novalnet_cc';
    $this->title        = MODULE_PAYMENT_NOVALNET_CC_TEXT_TITLE;
    $this->public_title = MODULE_PAYMENT_NOVALNET_CC_TEXT_PUBLIC_TITLE;
    $this->description  = MODULE_PAYMENT_NOVALNET_CC_TEXT_DESCRIPTION;
    $this->sort_order   = MODULE_PAYMENT_NOVALNET_CC_SORT_ORDER;
    $this->enabled      = ((MODULE_PAYMENT_NOVALNET_CC_STATUS == 'True') ? true : false);
    $this->proxy        = MODULE_PAYMENT_NOVALNET_CC_PROXY;
	$this->db        = $db;
	if (CHECKOUT_AJAX_STAT=='true') { $this->is_ajax = true; }

	// Check the tid in session and make the second call
	if($_SESSION['nn_tid_cc']){
		//Check the time limit
		if($_SESSION['max_time_cc'] && time() > $_SESSION['max_time_cc']){
			unset($_SESSION['nn_tid_cc']);
			$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode( utf8_encode(MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SESSION_ERROR ));
			if ($this->is_ajax)
				$_SESSION['checkout_payment_error'] = $payment_error_return;
			else
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
		}

		if( $_GET['new_novalnet_pin_cc'] == 'true'){
			$_SESSION['new_novalnet_pin_cc'] = true;
			$this->secondcall();
		}

		if(!$this->is_ajax && $_SESSION['email_reply_check_cc']=='Email Reply' && !isset($_SESSION['xml_resp_error_cc']))
			$this->secondCall();
	}

    // define callback types
    $this->isActivatedCallback = false;
	if(MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS != 'False'){
		$this->isActivatedCallback = true;
	}

    if ((int)MODULE_PAYMENT_NOVALNET_CC_ORDER_STATUS_ID > 0) {
      $this->order_status = MODULE_PAYMENT_NOVALNET_CC_ORDER_STATUS_ID;
    }

    if (is_object($order)) $this->update_status();
  }

  function update_status() {
    global $order;
	$this->enabled      = ((MODULE_PAYMENT_NOVALNET_CC_STATUS == 'True') ? true : false);
    if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_NOVALNET_CC_ZONE > 0) ) {
      $check_flag = false;
      $check_query = $this->db->db_query("select zone_id from ".TABLE_ZONES_TO_GEO_ZONES." where geo_zone_id = '".MODULE_PAYMENT_NOVALNET_CC_ZONE."' and zone_country_id = '".$order->billing['country']['id']."' order by zone_id");
          while (!$check->EOF) {
				if ($check->fields['zone_id'] < 1) {
					$check_flag = true;
					break;
				}
				elseif ($check->fields['zone_id'] == $order->billing['zone_id']) {
					$check_flag = true;
					break;
				}
				$check->MoveNext();
			}

      if ($check_flag == false) {
        $this->enabled = false;
      }
    }
  }

  function javascript_validation() {
    return false;
  }

  function selection() {
    global $xtPrice, $order, $_POST;
    $cc_no = $_POST['cc_no'];
    if(!$cc_no){$cc_no=$_SESSION['cc_no'];}
    $cc_exp_month = $_POST['cc_exp_month'];
    if(!$cc_exp_month){$cc_exp_month=$_SESSION['cc_exp_month'];}
    $cc_exp_year = $_POST['cc_exp_year'];
    if(!$cc_exp_year){$cc_exp_year=$_SESSION['cc_exp_year'];}
    $cc_cvc2 = $_POST['cc_cvc2'];
    if(!$cc_cvc2){$cc_cvc2=$_SESSION['cc_cvc2'];}
    $cc_holder = $_POST['cc_holder'];
    if(!$cc_holder){$cc_holder=$_SESSION['cc_holder'];}
    if(!$cc_holder){$cc_holder=$order->billing['firstname'].' '.$order->billing['lastname'];}

    $book_info = str_replace('$BOOKINFO', MODULE_PAYMENT_NOVALNET_CC_BOOK_REF, MODULE_PAYMENT_NOVALNET_CC_TEXT_BOOKING_INFO);

    $expires_month[] = array ('id' => '', 'text' => MODULE_PAYMENT_NOVALNET_CC_TEXT_SELECT);
    for ($i = 1; $i < 13; $i ++)
       $expires_month[] = array ('id' => sprintf('%02d', $i), 'text' => strftime('%B', mktime(0, 0, 0, $i, 1, 2000)));

    $today = getdate();
    $expires_year[] = array ('id' => '', 'text' => MODULE_PAYMENT_NOVALNET_CC_TEXT_SELECT);
    for ($i = $today['year']; $i < $today['year'] + 10; $i ++)
       $expires_year[] = array ('id' => strftime('%y', mktime(0, 0, 0, 1, 1, $i)), 'text' => strftime('%Y', mktime(0, 0, 0, 1, 1, $i)));

	if ($this->is_ajax || (!$this->is_ajax && !$_SESSION['nn_tid_cc'])) {
		$selection = array('id' => $this->code,
						   'module' => $this->public_title,
						   'fields' => array(array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_CARD_OWNER,
												   'field' => draw_input_field('cc_holder', $cc_holder, 'id="'.$this->code.'-cc_holder"' ),
												   'tag' => $this->code.'-cc_holder'),
											 array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_CC_NO,
												   'field' => draw_input_field('cc_no', $_SESSION['cc_no'], 'id="'.$this->code.'-cc_no"' ),
												   'tag' => $this->code.'-cc_no'),
											 array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_EXP_MONTH,
												   'field' =>  draw_pull_down_menu('cc_exp_month', $expires_month, $_SESSION['cc_exp_month'], 'id="'.$this->code.'-cc_exp_month"' ),
												   'tag' => $this->code.'-cc_exp_month'),
											 array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_EXP_YEAR,
												   'field' =>  draw_pull_down_menu('cc_exp_year', $expires_year, $_SESSION['cc_exp_year'], 'id="'.$this->code.'-cc_exp_year"' ),
													'tag' => $this->code.'-cc_exp_year'),
											 array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_CVC,
													'field' => draw_input_field('cc_cvc2', $_SESSION['cc_cvc2'], 'id="'.$this->code.'-cc_cvc2"'.'maxlength=3').MODULE_PAYMENT_NOVALNET_CC_TEXT_CVC2.$book_info,
													'tag' => $this->code.'-cc_cvc2')));

		$amount_check = $this->findTotalAmount();
		$_SESSION['amount_first_cc']=$amount_check;
		if($this->isActivatedCallback && strtolower($order->customer['country']['iso_code_2']) == 'de' && $amount_check >= MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_MIN_LIMIT )
		{
			if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'Email Reply' )
			{
				$selection['fields'][] = array( 'title' => MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_EMAIL, 'field' => draw_input_field ( 'user_email_cc', $_SESSION['user_email_cc'], 'id="'.$this->code.'-callback" ' ) );
			}
			else
			{
				if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'Callback (Telefon & Handy)' )
				{
					$selection['fields'][] = array( 'title' => MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS_TEL, 'field' => draw_input_field ( 'user_tel_cc', $_SESSION['user_tel_cc'], 'id="'.$this->code.'-callback" ' ) );
				}
				if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'SMS (nur Handy)' )
				{
					$selection['fields'][] = array( 'title' => MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS_MOB, 'field' => draw_input_field ( 'user_tel_cc', $_SESSION['user_tel_cc'], 'id="'.$this->code.'-callback" ' ) );
				}
			}
		}
	}
	//$amount_check = $this->findTotalAmount();
	$amount_check =$_SESSION['amount_first_cc'];
	if($this->isActivatedCallback && strtolower($order->customer['country']['iso_code_2']) == 'de' && $amount_check >= MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_MIN_LIMIT )
	{
		if ($this->is_ajax || (!$this->is_ajax && $_SESSION['nn_tid_cc'])) {

			if(!$this->is_ajax) {
				$selection = array('id' => $this->code,'module' => $this->public_title);
			}
			if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'Email Reply' ){
				if ($this->is_ajax) {
					$selection['fields'][] = array( 'title' => '','field' =>  MODULE_PAYMENT_NOVALNET_CC_EMAIL_INFO_DESC);
					$selection['fields'][] = array('title' => '', 'field' => draw_checkbox_field('email_replied_cc', '1', false).MODULE_PAYMENT_NOVALNET_CC_EMAIL_REPLY_INFO);
				} else
					$selection['fields'][] = array( 'title' => MODULE_PAYMENT_NOVALNET_CC_EMAIL_INPUT_REQUEST_DESC);
			} else {
				if ($this->is_ajax) {
					unset($_SESSION['email_reply_check_cc']);
					if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'Callback (Telefon & Handy)' )
					{
						$selection['fields'][] = array( 'title' => '','field' =>  MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS_TEL_NUMBER);
					}
					if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'SMS (nur Handy)' )
					{
						$selection['fields'][] = array( 'title' => '','field' =>  MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS_MOB_NUMBER);
					}

					$selection['fields'][] = array( 'title' => '','field' =>  MODULE_PAYMENT_NOVALNET_CC_PIN_INFO_DESC);

					$selection['fields'][] = array( 'title' => MODULE_PAYMENT_NOVALNET_CC_PIN_INPUT_REQUEST_DESC, 'field' => draw_input_field( 'novalnet_pin_cc', '', 'id="'.$this->code.'-callback" '.' maxlength="4" size="4" ') );

					$selection['fields'][] = array('title' => '', 'field' => draw_checkbox_field('forgot_pin_cc', '1', false, 'id="'.$this->code.'-forgotpin"' ).MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS_NEW_PIN);

					$selection['fields'][] = array('title' => '', 'field' => MODULE_PAYMENT_NOVALNET_CC_FORGOT_PIN_DIV);
				} else {

					$selection['fields'][] = array( 'title' => MODULE_PAYMENT_NOVALNET_CC_PIN_INPUT_REQUEST_DESC, 'field' => draw_input_field( 'novalnet_pin_cc', '', 'id="'.$this->code.'-callback" '.' maxlength="4" size="4" ') );

					$selection['fields'][] = array( 'title' => '<a href="'.href_link( FILENAME_CHECKOUT_PAYMENT, 'new_novalnet_pin_cc=true', 'SSL', true, false).'">'.MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS_NEW_PIN.'</a>') ;
				}
			}
		}
	}
    if(function_exists(get_percent))
    {
        $selection['module_cost'] = $GLOBALS['ot_payment']->get_percent($this->code);
    }
    return $selection;
  }

  ### Precheck to Evaluate the Bank Datas ###
  function pre_confirmation_check($vars) {

    global $_POST, $order;

	// Check shipping methods are selected or not;
	if(!$order->info['shipping_method']){
		$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode( utf8_encode(MODULE_PAYMENT_NOVALNET_CC_REQUEST_FOR_CHOOSE_SHIPPING_METHOD ));
		$_SESSION['checkout_payment_error'] = $payment_error_return;
		return;
	}

	if ($this->is_ajax) {
		$_POST = $vars;
	} else {
		$_POST = $_POST;
	}

	$_POST['cc_holder']    	= trim($_POST['cc_holder']);
	$_POST['cc_no']        	= trim($_POST['cc_no']);
	$_POST['cc_exp_month'] 	= trim($_POST['cc_exp_month']);
	$_POST['cc_exp_year']  	= trim($_POST['cc_exp_year']);
	$_POST['cc_cvc2']      	= trim($_POST['cc_cvc2']);

	if(isset($_POST['user_tel_cc'])) {
		$_POST['user_tel_cc'] 		= trim($_POST['user_tel_cc']);
	}
	if(isset($_POST['user_email_cc'])) {
		$_POST['user_email_cc'] 		= trim($_POST['user_email_cc']);
	}
	if(isset($_POST['novalnet_pin_cc'])) {
		$_POST['novalnet_pin_cc'] 		= trim($_POST['novalnet_pin_cc']);
	}
	if($_SESSION['nn_tid_cc'])
    {
		// check pin
		if($this->is_ajax && $_POST['forgot_pin_cc'] && !$_POST['novalnet_pin_cc'])
		{
			$_SESSION['new_novalnet_pin_cc'] = true;
			$this->secondCall();
			return;
		}
		if($this->is_ajax && MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'Email Reply' )
		{
			if($this->is_ajax && !$_POST['email_replied_cc'])
			{
				$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode( utf8_encode(MODULE_PAYMENT_NOVALNET_CC_EMAIL_REPLY_CHECKBOX_INFO ));
				if ($this->is_ajax) {
						$_SESSION['checkout_payment_error'] = $payment_error_return;
				} else {
					redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
				}
			}
			else {
				$_SESSION['email_reply_check_cc']='Email Reply';
			}
		}

		if(isset($_POST['novalnet_pin_cc']) && isset($_SESSION['nn_tid_cc'])) {

			if( !is_numeric( $_POST['novalnet_pin_cc'] ) || strlen( $_POST['novalnet_pin_cc'] ) != 4 )
			{
				$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode( utf8_encode(MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS_PIN_NOTVALID) );
				if ($this->is_ajax) {
						$_SESSION['checkout_payment_error'] = $payment_error_return;
				} else {
					redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
				}
			}
			else
			{
				if( $_POST['novalnet_pin_cc'] )
				$_SESSION['novalnet_pin_cc'] = $_POST['novalnet_pin_cc'];
			}
		}
		return;
	}
	else {
		$error = '';
		if ($this->is_ajax || (!$this->is_ajax && !isset($_SESSION['nn_tid_cc']))) {
			if (defined('MODULE_PAYMENT_NOVALNET_CC_MANUAL_CHECK_LIMIT') and MODULE_PAYMENT_NOVALNET_CC_MANUAL_CHECK_LIMIT){
			  if ( (!defined('MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID2') or !MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID2 or preg_match('/[^\d]/', MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID2)) or (!defined('MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID2') or !MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID2 or preg_match('/[^\d]/', MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID2))){
				$error = 'Product-ID2 and/or Tariff-ID2 missing';
			  }
			}

			if(!MODULE_PAYMENT_NOVALNET_CC_VENDOR_ID || !MODULE_PAYMENT_NOVALNET_CC_AUTH_CODE || !MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID || !MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID)
			{
			  $error .= MODULE_PAYMENT_NOVALNET_CC_TEXT_JS_NN_MISSING;
			}
			elseif(!$_POST['cc_holder'] || strlen($_POST['cc_holder']) < MODULE_PAYMENT_NOVALNET_CC_TEXT_CARD_OWNER_LENGTH)
			{
			  $error .= MODULE_PAYMENT_NOVALNET_CC_TEXT_JS_CARD_OWNER;
			}
			elseif(!$_POST['cc_no'] || strlen($_POST['cc_no']) < MODULE_PAYMENT_NOVALNET_CC_TEXT_CC_NO_LENGTH){
			  $error .= MODULE_PAYMENT_NOVALNET_CC_TEXT_JS_CC_NO;
			}
			elseif(!$_POST['cc_exp_month'] || strlen($_POST['cc_exp_month'])<MODULE_PAYMENT_NOVALNET_CC_TEXT_EXP_MONTH_LENGTH)
			{
			  $error .= MODULE_PAYMENT_NOVALNET_CC_TEXT_JS_EXP_MONTH;
			}
			elseif(!$_POST['cc_exp_year']  || strlen($_POST['cc_exp_year']) <MODULE_PAYMENT_NOVALNET_CC_TEXT_EXP_YEAR_LENGTH)
			{
			  $error .= MODULE_PAYMENT_NOVALNET_CC_TEXT_JS_EXP_YEAR;

			}
			elseif(!$_POST['cc_cvc2'] || (strlen($_POST['cc_cvc2']) < MODULE_PAYMENT_NOVALNET_CC_TEXT_CVC_LENGTH))
			{
			  $error .= MODULE_PAYMENT_NOVALNET_CC_TEXT_JS_CVC;
			}
			elseif( $_POST['cc_cvc2']=='000' || $_POST['cc_cvc2']<1)
			{
			  $error .= MODULE_PAYMENT_NOVALNET_CC_TEXT_JS_CVC2;
			}

			$_SESSION['cc_holder']    = $_POST['cc_holder'];
			$_SESSION['cc_no']        = $_POST['cc_no'];
			$_SESSION['cc_exp_month'] = $_POST['cc_exp_month'];
			$_SESSION['cc_exp_year']  = $_POST['cc_exp_year'];
			$_SESSION['cc_cvc2']      = $_POST['cc_cvc2'];
			if (isset($_POST['user_tel_cc']))
			{ $_SESSION['user_tel_cc']  = $_POST['user_tel_cc']; }
			if (isset($_POST['user_email_cc']))
			{ $_SESSION['user_email_cc']  = $_POST['user_email_cc']; }

			// Callback stuff....
			//$amount_check = $this->findTotalAmount();
			$amount_check = $_SESSION['amount_first_cc'];

			if( $this->isActivatedCallback && strtolower($order->customer['country']['iso_code_2']) == 'de' && $amount_check >= MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_MIN_LIMIT )
			{
				if($error=='') {
					//checking email address
					if (isset($_POST['user_email_cc']))
					{
						if (!preg_match("#^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})#", $_POST['user_email_cc'])){
							$error .= utf8_decode( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_EMAIL_NOTVALID );
						}
					}

					//checking telephone number
					if (isset($_POST['user_tel_cc']))
					{
						if( strlen( $_POST['user_tel_cc'] ) < 8 || !is_numeric( $_POST['user_tel_cc'] )  )
						{
							$error .= utf8_decode( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS_TEL_NOTVALID );
						}
					}
				}

				if($error!='') {
				  $payment_error_return = 'payment_error='.$this->code.'&error='.urlencode(utf8_encode($error));

					if ($this->is_ajax) {
						$_SESSION['checkout_payment_error'] = $payment_error_return;
					} else {
						redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
					}

				}
				else{
						$this->before_process($vars);
						if (!$this->is_ajax) {
							redirect(href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
						}
				}

			}
		}
		if($error!='') {
			$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode(utf8_encode($error));
			if ($this->is_ajax) {
				$_SESSION['checkout_payment_error'] = $payment_error_return;
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}

		}
	}
  }

  //This is user defined function used for getting order amount in cents with tax
  public function findTotalAmount(){
		global $order;
		if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
		  $total = $order->info['total'] + $order->info['tax'];
		} else {
		  $total = $order->info['total'];
		}
		if (preg_match('/[^\d\.]/', $total) or !$total){
			### $amount contains some unallowed chars or empty ###
			$err                      = 'amount ('.$total.') is empty or has a wrong format';
			$payment_error_return     = 'payment_error='.$this->code.'&error='.utf8_encode($err);
			if ($this->is_ajax) {
				$_SESSION['checkout_payment_error'] = $payment_error_return;
				//return;
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
		}
		$amount = sprintf('%0.2f', $total);
		$amount = preg_replace('/^0+/', '', $amount);
		$amount = str_replace('.', '', $amount);
	return $amount;
  }

	function confirmation() {
		global $_POST, $order;

		if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
		  $total = $order->info['total'] + $order->info['tax'];
		} else {
		  $total = $order->info['total'];
		}
		$_SESSION['nn_total_cc'] = sprintf('%.2f', $total);
		$_SESSION['amount_first_cc']=sprintf('%.2f', $total);
		$cardnoLength = strlen(str_replace(' ','',$_SESSION['cc_no']));
		$crdNo = str_replace(' ','',$_SESSION['cc_no']);
		$cardnoInfo = '';
		$chkLength = $cardnoLength-5;
		for($i=0;$i<$cardnoLength;$i++){
			if($i >= $chkLength){
				$cardnoInfo .= '*';
			}else{
				$cardnoInfo .= $crdNo[$i];
			}
		}
		$confirmation = array('fields' => array(array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_CARD_OWNER,
		                      'field' => $_SESSION['cc_holder']),
		                array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_CC_NO,
		                      'field' => $cardnoInfo),
		                array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_EXP_MONTH,
		                     'field' =>  $_SESSION['cc_exp_month']),
		                array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_EXP_YEAR,
		                      'field' => $_SESSION['cc_exp_year']),
		                array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_CVC,
		                      'field' => '***')));

		return $confirmation;
	}

	  ### Build the data and actions to process when the "Submit" button is pressed on the order-confirmation screen. ###
	  ### These are hidden fields on the checkout confirmation page ###
	  // @return string
	  function process_button() {
		global $_POST;
		$process_button_string = draw_hidden_field('cc_holder',    $_POST['cc_holder']) .
								 draw_hidden_field('cc_no',        $_POST['cc_no']) .
								 draw_hidden_field('cc_exp_month', $_POST['cc_exp_month']) .
								 draw_hidden_field('cc_exp_year',  $_POST['cc_exp_year']) .
								 draw_hidden_field('cc_cvc2',      $_POST['cc_cvc2']);

		return $process_button_string;
	  }

  	function secondCall()
	{
		// If customer forgets PIN, send a new PIN
		if( $_SESSION['new_novalnet_pin_cc'] )
			$request_type = 'TRANSMIT_PIN_AGAIN';
		else
	        $request_type = 'PIN_STATUS';

		if($_SESSION['email_reply_check_cc']=='Email Reply')
			 $request_type = 'REPLY_EMAIL_STATUS';

		if( $_SESSION['new_novalnet_pin_cc'] )
			$_SESSION['new_novalnet_pin_cc'] = false;


		if($request_type == 'REPLY_EMAIL_STATUS') {
			$xml = '<?xml version="1.0" encoding="UTF-8"?>
				<nnxml>
		  			<info_request>
			    		<vendor_id>'.MODULE_PAYMENT_NOVALNET_CC_VENDOR_ID.'</vendor_id>
			    		<vendor_authcode>'.MODULE_PAYMENT_NOVALNET_CC_AUTH_CODE.'</vendor_authcode>
			    		<request_type>'.$request_type.'</request_type>
			    		<tid>'.$_SESSION['nn_tid_cc'].'</tid>
		  			</info_request>
				</nnxml>';
		}
		else {
			$xml = '<?xml version="1.0" encoding="UTF-8"?>
				<nnxml>
		  			<info_request>
			    		<vendor_id>'.MODULE_PAYMENT_NOVALNET_CC_VENDOR_ID.'</vendor_id>
			    		<vendor_authcode>'.MODULE_PAYMENT_NOVALNET_CC_AUTH_CODE.'</vendor_authcode>
			    		<request_type>'.$request_type.'</request_type>
			    		<tid>'.$_SESSION['nn_tid_cc'].'</tid>
			    		<pin>'.$_SESSION['novalnet_pin_cc'].'</pin>
		  			</info_request>
				</nnxml>';

		}
		$xml_response = $this->curl_xml_post( $xml );

		// Parse XML Response to object
		$xml_response = simplexml_load_string( $xml_response );

		if( $xml_response->status != 100 )
		{
			$_SESSION['xml_resp_error_cc']=$xml_response->status_message;
			$payment_error_return = 'payment_error='.$this->code.'&error='.utf8_encode($_SESSION['xml_resp_error_cc']);
			if ($this->is_ajax) {
				$_SESSION['checkout_payment_error'] = $payment_error_return;
				if($request_type == 'PIN_STATUS' || $request_type == 'REPLY_EMAIL_STATUS') {
					redirect(href_link(FILENAME_CHECKOUT, $payment_error_return, 'SSL', true, false));
				}
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
		}
		else
		{
			$array = (array) $xml_response;
			// add tid, because it's missing in the response
			$array['tid'] = $_SESSION['nn_tid_cc'];
			$array['statusdesc'] = $array['status_message']; // Param-name is changed
			$array['test_mode'] = $_SESSION['test_mode_cc'];
			return $array;
		}
	}

    public function curl_xml_post( $request )
	{
	    $ch = curl_init( "https://payport.novalnet.de/nn_infoport.xml" );
	    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
		curl_setopt($ch, CURLOPT_POST, 1);  // a non-zero parameter tells the library to do a regular HTTP post.
		curl_setopt($ch, CURLOPT_POSTFIELDS, $request);  // add POST fields
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);  // don't allow redirects
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // decomment it if you want to have effective ssl checking
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // decomment it if you want to have effective ssl checking
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  // return into a variable
		curl_setopt($ch, CURLOPT_TIMEOUT, 240);  // maximum time, in seconds, that you'll allow the CURL functions to take

		## establish connection
		$xml_response = curl_exec($ch);

		## determine if there were some problems on cURL execution
		$errno = curl_errno($ch);
		$errmsg = curl_error($ch);

		###bug fix for PHP 4.1.0/4.1.2 (curl_errno() returns high negative value in case of successful termination)
		if($errno < 0) $errno = 0;
		##bug fix for PHP 4.1.0/4.1.2

		if($debug)
		{
			print_r(curl_getinfo($ch));
			echo "\n<br /><br />\n\n\nperform_https_request: cURL error number:".$errno."\n<br />\n\n";
			echo "\n\n\nperform_https_request: cURL error:".$errmsg."\n<br />\n\n";
		}

		#close connection
		curl_close($ch);

		return $xml_response;
	}

  ### Store the BANK info to the order ###
  ### This sends the data to the payment gateway for processing and Evaluates the Bankdatas for acceptance and the validity of the Bank Details ###
  function before_process($vars) {
    global $_POST, $order, $currencies, $customer_id;
	// Setting callback type // see constructor
	// First call is done, so check PIN / second call...
	if( $_SESSION['nn_tid_cc'] && $this->isActivatedCallback){
		if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'Email Reply' )
			$_SESSION['email_reply_check_cc']='Email Reply';
		else
			unset($_SESSION['email_reply_check_cc']);

		if($this->is_ajax && $_POST['forgot_pin_cc'] && !$_POST['novalnet_pin_cc'])
			$_SESSION['new_novalnet_pin_cc']=true;
		else
			$_SESSION['new_novalnet_pin_cc']=false;

		$aryResponse = $this->secondCall();
		if($aryResponse){
			$old_comments = $order->info['comments'];
			$order->info['comments'] = "";
			//Test mode based on the responsone test mode value
			$test_mode = (strtolower(MODULE_PAYMENT_NOVALNET_CC_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_CC_TEST_MODE == '1')? 1: 0;
			if($test_mode){
			//if($aryResponse['test_mode'] == 1){
				$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_CC_TEST_ORDER_MESSAGE;
			}
			$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_CC_TID_MESSAGE.$aryResponse['tid'];
		}

		return;
	}

    if ($this->is_ajax && $this->isActivatedCallback ) {
		if(count($_POST)==0 || $_POST=='')
			$_POST = $vars;
	} else {
		if(count($_POST)==0 || $_POST=='')
			$_POST = $_POST;
	}

    #Get the required additional customer details from DB
    $customer_query = $this->db->db_query("SELECT customers_gender, customers_dob, customers_fax FROM ". TABLE_CUSTOMERS." WHERE customers_id='". (int)$customer_id ."'");
      if ($customer_query->_numOfRows) {
		$customer['customers_gender']=$customer_query->fields['customers_gender'];
		$customer['customers_dob']=$customer_query->fields['customers_dob'];
		$customer['customers_fax']=$customer_query->fields['customers_fax'];
	}

    ### Process the payment to paygate ##
    $url = 'https://payport.novalnet.de/paygate.jsp';
	//find total amount in cents (Euro * 100)
	//$amount = $this->findTotalAmount();
	$amount = $_SESSION['amount_first_cc'];
    $product_id         = MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID;
    $tariff_id          = MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID;
    $manual_check_limit = trim(MODULE_PAYMENT_NOVALNET_CC_MANUAL_CHECK_LIMIT);
    $manual_check_limit = str_replace(',', '', $manual_check_limit);
    $manual_check_limit = str_replace('.', '', $manual_check_limit);

    if($manual_check_limit && $amount>=$manual_check_limit)
    {
        $product_id = MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID2;
        $tariff_id = MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID2;
    }

    $user_ip   = $this->getRealIpAddr();

	//set the user telephone
	if($_SESSION['user_tel_cc']){
		$user_telephone = $_SESSION['user_tel_cc'];
	}else{
		$user_telephone	= $order->customer['telephone'];
	}
	//set the user email
	if($_SESSION['user_email_cc']){
		$user_email = $_SESSION['user_email_cc'];
	}else{
		$user_email	= $order->customer['email_address'];
	}
	// set post params
	if( $this->isActivatedCallback && strtolower($order->customer['country']['iso_code_2']) == 'de' && $amount >= MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_MIN_LIMIT ){
		if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'Callback (Telefon & Handy)' )
		{
			$this->callback_type = '&pin_by_callback=1';
			$url_telephone = '&tel='.$user_telephone;
		}
		if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'SMS (nur Handy)' )
		{
			$this->callback_type = '&pin_by_sms=1';
			$url_telephone = '&mobile='.$user_telephone;
		}
		if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'Email Reply' )
		{
			$this->callback_type = '&reply_email_check=1';
		}
	}
    $urlparam  = 'vendor='.MODULE_PAYMENT_NOVALNET_CC_VENDOR_ID.'&product='.$product_id.'&key=6&tariff='.$tariff_id;
    $urlparam .= '&auth_code='.MODULE_PAYMENT_NOVALNET_CC_AUTH_CODE.'&currency='.$order->info['currency'];
    $urlparam .= '&amount='.$amount.'&cc_holder='.$this->html_to_utf8($_POST['cc_holder']).'&cc_no='.$_POST['cc_no'];
    $urlparam .= '&cc_exp_month='.$_POST['cc_exp_month'].'&cc_exp_year='.$_POST['cc_exp_year'];
    $urlparam .= '&cc_cvc2='.$_POST['cc_cvc2'].'&first_name='.$this->html_to_utf8($order->customer['firstname']).'&last_name='.$this->html_to_utf8($order->customer['lastname']);
    $urlparam .= '&street='.$this->html_to_utf8($order->customer['street_address']).'&city='.$this->html_to_utf8($order->customer['city']).'&zip='.$order->customer['postcode'];
    $urlparam .= '&country='.$order->customer['country']['iso_code_2'].'&email='.$user_email;
    $urlparam .= '&search_in_street=1'.$url_telephone.'&remote_ip='.$user_ip;
    $urlparam .= '&gender='.$customer['customers_gender'].'&birth_date='.$customer['customers_dob'].'&fax='.$customer['customers_fax'];
    $urlparam .= '&language='.MODULE_PAYMENT_NOVALNET_CC_TEXT_LANG;
    $test_mode = (strtolower(MODULE_PAYMENT_NOVALNET_CC_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_CC_TEST_MODE == '1')? 1: 0;
    $urlparam .= '&test_mode='.$test_mode;
	// For PIN by call back
	$urlparam .= $this->callback_type;

    list($errno, $errmsg, $data) = $this->perform_https_request($url, $urlparam);

    if ($errno or $errmsg) {
      ### Payment Gateway Error ###
      $order->info['comments'] .= '. func perform_https_request returned Errorno : '.$errno.', Error Message : '.$errmsg;
      $payment_error_return = 'payment_error='.$this->code.'&error=' .utf8_encode($errmsg). '('.$errno.')';
	  if ($this->is_ajax) {
		$_SESSION['checkout_payment_error'] = $payment_error_return;
	  } else {
		redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
	  }
    }

    #capture the result and message and other parameters from response data '$data' in an array
	parse_str( $data, $aryResponse );

    if($aryResponse['status']==100)
    {
		$order->info['comments'] = "";
		### Passing through the Transaction ID from Novalnet's paygate into order-info ###
		if( $this->isActivatedCallback && strtolower($order->customer['country']['iso_code_2']) == 'de' && $amount >= MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_MIN_LIMIT ){
			$_SESSION['nn_tid_cc'] = $aryResponse['tid'];
			// To avoide payment method confussion add code in session
			//set session for maximum time limit to 30 minutes
			$_SESSION['max_time_cc'] = time() + (30 * 60);
			//TEST BILLING MESSAGE BASED ON THE RESPONSE TEST MODE
			$test_mode = (strtolower(MODULE_PAYMENT_NOVALNET_CC_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_CC_TEST_MODE == '1')? 1: 0;
			if($test_mode){
				$_SESSION['test_mode_cc'] = $test_mode;
			}
			if ($this->is_ajax) {
				if( MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS == 'Email Reply' )
				{
					$checkoutmsg =MODULE_PAYMENT_NOVALNET_CC_EMAIL_REPLY_CHECK_MSG;
					$payment_error_return     = 'payment_error='.$this->code.'&error='.utf8_encode($checkoutmsg);
					$_SESSION['checkout_payment_error'] = $payment_error_return;
				}
				else {
					$checkoutmsg =MODULE_PAYMENT_NOVALNET_CC_PIN_CHECK_MSG;
					$payment_error_return     = 'payment_error='.$this->code.'&error='.utf8_encode($checkoutmsg);
					$_SESSION['checkout_payment_error'] = $payment_error_return;
				}
			}
		}
		else{
			$test_mode = (strtolower(MODULE_PAYMENT_NOVALNET_CC_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_CC_TEST_MODE == '1')? 1: 0;
			if($test_mode){
				$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_CC_TEST_ORDER_MESSAGE;
			}
			$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_CC_TID_MESSAGE.$aryResponse['tid'];
		}
    }
    else
    {
      ### Passing through the Error Response from Novalnet's paygate into order-info ###
      $order->info['comments'] .= '. Novalnet Error Code : '.$aryResponse['status'].', Novalnet Error Message : '.$aryResponse['status_desc'];
      $payment_error_return = 'payment_error='.$this->code.'&error='.urlencode(utf8_encode($aryResponse['status_desc']));
		if ($this->is_ajax) {
			//$_SESSION['checkout_payment_error'] = $payment_error_return;
			redirect(href_link(FILENAME_CHECKOUT, $payment_error_return, 'SSL', true, false));
		} else {
			 redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
		}
    }
	return;
  }

  ### Realtime accesspoint for communication to the Novalnet paygate ###
  function perform_https_request($nn_url, $urlparam)
  {
      $debug = 0;#set it to 1 if you want to activate the debug mode

      if($debug) print "<br />perform_https_request: $nn_url<br />\n\r\n";
      if($debug) print "perform_https_request: $urlparam<br />\n\r\n";

      ## some prerquisites for the connection
      $ch = curl_init($nn_url);
      curl_setopt($ch, CURLOPT_POST, 1);  // a non-zero parameter tells the library to do a regular HTTP post.
      curl_setopt($ch, CURLOPT_POSTFIELDS, $urlparam);  // add POST fields
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);  // don't allow redirects
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // decomment it if you want to have effective ssl checking
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // decomment it if you want to have effective ssl checking
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  // return into a variable
      curl_setopt($ch, CURLOPT_TIMEOUT, 240);  // maximum time, in seconds, that you'll allow the CURL functions to take
      if ($this->proxy) {curl_setopt($ch, CURLOPT_PROXY, $this->proxy); }

      ## establish connection
      $data = curl_exec($ch);
      $data = $this->ReplaceSpecialGermanChars($data);

      ## determine if there were some problems on cURL execution
      $errno = curl_errno($ch);
      $errmsg = curl_error($ch);

      ###bug fix for PHP 4.1.0/4.1.2 (curl_errno() returns high negative value in case of successful termination)
      if($errno < 0) $errno = 0;
      ##bug fix for PHP 4.1.0/4.1.2

      if($debug)
      {
        print_r(curl_getinfo($ch));
        echo "\n<br /><br />\n\n\nperform_https_request: cURL error number:".$errno."\n<br />\n\n";
        echo "\n\n\nperform_https_request: cURL error:".$errmsg."\n<br />\n\n";
      }

      #close connection
      curl_close($ch);

      ## read and return data from novalnet paygate
      if($debug) print "<br />\n\n".$data."\n<br />\n\n";

      return array ($errno, $errmsg, $data);
  }

  function isPublicIP($value)
  {
        if(!$value || count(explode('.',$value))!=4) return false;
        return !preg_match('~^((0|10|172\.16|192\.168|169\.254|255|127\.0)\.)~', $value);
  }

  ### get the real Ip Adress of the User ###
  function getRealIpAddr()
  {
        if($this->isPublicIP($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
        if($iplist=explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            if($this->isPublicIP($iplist[0])) return $iplist[0];
        }
        if ($this->isPublicIP($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
        if ($this->isPublicIP($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
        if ($this->isPublicIP($_SERVER['HTTP_FORWARDED_FOR']) ) return $_SERVER['HTTP_FORWARDED_FOR'];

        return $_SERVER['REMOTE_ADDR'];
  }

  ### replace the Special German Charectors ###
  function ReplaceSpecialGermanChars($string){
     $what = array("ä", "ö", "ü", "Ä", "Ö", "Ü", "ß");
     $how = array("ae", "oe", "ue", "Ae", "Oe", "Ue", "ss");

     $string = str_replace($what, $how, $string);

     return $string;
  }

  ### Send the order detail to Novalnet ###
  function after_process() {
    global $order, $customer_id, $insert_id;
    if ($this->order_status){
      $this->db->db_query("UPDATE ".TABLE_ORDERS." SET orders_status='".$this->order_status."' WHERE orders_id='".$insert_id."'");
    }

    $product_id = MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID;
    $tariff_id = MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID;

    ### Pass the Order Reference to paygate ##
    $url = 'https://payport.novalnet.de/paygate.jsp';
    $urlparam = 'vendor='.MODULE_PAYMENT_NOVALNET_CC_VENDOR_ID.'&product='.$product_id.'&key=6&tariff='.$tariff_id;
	$urlparam .= '&order_no='.$insert_id;
    $urlparam .= '&auth_code='.MODULE_PAYMENT_NOVALNET_CC_AUTH_CODE.'&status=100&tid='.$_SESSION['nn_tid_cc'].'&reference=BNR-'.$insert_id.'&vwz2='.MODULE_PAYMENT_NOVALNET_CC_TEXT_ORDERNO.''.$insert_id.'&vwz3='.MODULE_PAYMENT_NOVALNET_CC_TEXT_ORDERDATE.''.date('Y-m-d H:i:s');
    list($errno, $errmsg, $data) = $this->perform_https_request($url, $urlparam);
	unset($_SESSION['nn_tid_cc']);
	unset($_SESSION['max_time_cc']);
	unset($_SESSION['cc_holder']);
	unset($_SESSION['cc_no']);
	unset($_SESSION['cc_exp_month']);
	unset($_SESSION['cc_exp_year']);
	unset($_SESSION['cc_cvc2']);
	unset($_SESSION['test_mode_cc']);
	unset($_SESSION['user_tel_cc']);
	unset($_SESSION['user_email_cc']);
	unset($_SESSION['email_reply_check_cc']);
	unset($_SESSION['xml_resp_error_cc']);
	unset($_SESSION['amount_first_cc']);

    ### Implement here the Emailversand and further functions, incase if you want to send a own email ###

    return false;
  }

	function get_error() {
		global $_GET;
		$error = array('title' => MODULE_PAYMENT_NOVALNET_CC_TEXT_ERROR,
		               'error' => stripslashes(urldecode($_GET['error'])));

		return $error;
	}

	function check() {
		if (!isset($this->_check)) {
			$check_query = $this->db->db_query("select configuration_value from ".TABLE_CONFIGURATION." where configuration_key = 'MODULE_PAYMENT_NOVALNET_CC_STATUS'");
			$this->_check = $check_query->_numOfRows;
		}
		return $this->_check;
	}

	function install() {
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_ALLOWED', '', '6', '0', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS', 'False', '6', '3', 'cfg_select_option(array( \'False\', \'Callback (Telefon & Handy)\', \'SMS (nur Handy)\', \'Email Reply\'), ', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_MIN_LIMIT', '', '6', '2', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_STATUS', 'True', '6', '1', 'cfg_select_option(array(\'True\', \'False\'), ', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_TEST_MODE', 'True', '6', '2', 'cfg_select_option(array(\'True\', \'False\'), ', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_VENDOR_ID', '', '6', '3', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_AUTH_CODE', '', '6', '4', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID', '', '6', '5', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID', '', '6', '6', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_MANUAL_CHECK_LIMIT', '', '6', '7', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID2', '', '6', '8', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID2', '', '6', '9', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_BOOK_REF', '', '6', '10', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_SORT_ORDER', '0', '6', '11', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, use_function, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_ORDER_STATUS_ID', '0', '6', '12', 'cfg_pull_down_order_statuses(', 'get_order_status_name', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, use_function, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_ZONE', '0', '6', '13', 'get_zone_class_title', 'cfg_pull_down_zone_classes(', now())");
		$this->db->db_query("INSERT INTO ".TABLE_CONFIGURATION." (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_CC_PROXY', '', '6', '13', now())");
	}

	function remove() {
		$this->db->db_query("DELETE FROM ".TABLE_CONFIGURATION." where configuration_key in ('".implode("', '", $this->keys())."')");
	}

	function keys() {
		return array('MODULE_PAYMENT_NOVALNET_CC_ALLOWED','MODULE_PAYMENT_NOVALNET_CC_STATUS', 'MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_SMS','MODULE_PAYMENT_NOVALNET_CC_PIN_BY_CALLBACK_MIN_LIMIT','MODULE_PAYMENT_NOVALNET_CC_TEST_MODE', 'MODULE_PAYMENT_NOVALNET_CC_VENDOR_ID', 'MODULE_PAYMENT_NOVALNET_CC_AUTH_CODE', 'MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID', 'MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID', 'MODULE_PAYMENT_NOVALNET_CC_MANUAL_CHECK_LIMIT', 'MODULE_PAYMENT_NOVALNET_CC_PRODUCT_ID2', 'MODULE_PAYMENT_NOVALNET_CC_TARIFF_ID2', 'MODULE_PAYMENT_NOVALNET_CC_BOOK_REF', 'MODULE_PAYMENT_NOVALNET_CC_SORT_ORDER', 'MODULE_PAYMENT_NOVALNET_CC_ORDER_STATUS_ID', 'MODULE_PAYMENT_NOVALNET_CC_ZONE', 'MODULE_PAYMENT_NOVALNET_CC_PROXY');
	}

	function html_to_utf8 ($data){
		return preg_replace("/\\&\\#([0-9]{3,10})\\;/e", '$this->_html_to_utf8("\\1")', $data);
	}

	function _html_to_utf8 ($data){
		if ($data > 127){
			$i = 5;
			while (($i--) > 0){
				if ($data != ($a = $data % ($p = pow(64, $i)))){
					$ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p));
					for ($i; $i > 0; $i--)
						$ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p));
					break;
				}
			}
		} else
			$ret = "&#$data;";

		return $ret;
	}

	function debug2($object, $filename, $debug = false){
		if (!$debug){return;}
		$fh = fopen("/tmp/$filename", 'a+');
		if (gettype($object) == 'object' or gettype($object) == 'array'){
			fwrite($fh, serialize($object));
		}else{
			fwrite($fh, date('Y-m-d H:i:s').' '.$object);
		}
		fwrite($fh, "<hr />\n");
		fclose($fh);
	}
}